#!/usr/bin/env node
/**
 * 验证现有组件的完整性
 *
 * 用法:
 *   npm run workflow:validate-all ComponentName
 *
 * 功能:
 * - 检查22个必需产物是否完整
 * - 验证所有Phase的质量门控
 * - 生成产物完整性报告
 */

const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');

const ROOT = process.cwd();
const MANIFEST_PATH = path.join(ROOT, 'Workflow/FigmaMCPWorkflow/phase-manifest.json');

/**
 * 主验证函数
 */
async function validateComponent(componentName) {
  console.log(`\n${'='.repeat(60)}`);
  console.log(`🔍 组件完整性验证`);
  console.log(`   组件: ${componentName}`);
  console.log(`${'='.repeat(60)}\n`);

  const manifest = loadManifest();
  const componentDir = path.join(ROOT, componentName);

  if (!fs.existsSync(componentDir)) {
    console.error(`❌ 组件目录不存在: ${componentDir}`);
    process.exit(1);
  }

  const results = {
    component: componentName,
    timestamp: new Date().toISOString(),
    phases: {},
    summary: {
      totalArtifacts: 0,
      existingArtifacts: 0,
      missingArtifacts: 0,
      completenessRate: 0
    }
  };

  // 验证各Phase
  for (const [phaseName, phaseConfig] of Object.entries(manifest.phases)) {
    console.log(`\n📋 验证 ${phaseName}...`);

    const phaseResult = await validatePhase(phaseName, phaseConfig, componentName);
    results.phases[phaseName] = phaseResult;

    results.summary.totalArtifacts += phaseResult.totalArtifacts;
    results.summary.existingArtifacts += phaseResult.existingArtifacts;
    results.summary.missingArtifacts += phaseResult.missingArtifacts;
  }

  results.summary.completenessRate = results.summary.totalArtifacts > 0
    ? (results.summary.existingArtifacts / results.summary.totalArtifacts)
    : 1;

  // 生成报告
  const reportPath = path.join(componentDir, 'completeness-report.json');
  fs.writeFileSync(reportPath, JSON.stringify(results, null, 2));

  // 打印总结
  console.log(`\n${'='.repeat(60)}`);
  console.log(`📊 验证总结`);
  console.log(`   产物完整性: ${(results.summary.completenessRate * 100).toFixed(1)}%`);
  console.log(`   存在: ${results.summary.existingArtifacts}/${results.summary.totalArtifacts}`);
  console.log(`   缺失: ${results.summary.missingArtifacts}`);
  console.log(`\n   报告: ${reportPath}`);
  console.log(`${'='.repeat(60)}\n`);

  if (results.summary.completenessRate < 1) {
    console.log(`⚠️  发现缺失产物，建议执行: npm run workflow:auto ${componentName}`);
  } else {
    console.log(`✅ 所有产物完整`);
  }
}

/**
 * 验证单个Phase
 */
async function validatePhase(phaseName, phaseConfig, componentName) {
  const result = {
    phase: phaseName,
    totalArtifacts: 0,
    existingArtifacts: 0,
    missingArtifacts: 0,
    artifacts: [],
    gateValidation: null
  };

  // 验证产物
  const artifacts = [
    ...(phaseConfig.outputs.intermediate || []),
    ...(phaseConfig.outputs.checkpoints || []),
    ...(phaseConfig.outputs.system || [])
  ];

  for (const artifact of artifacts) {
    if (!artifact.required) continue;

    result.totalArtifacts++;

    const artifactPath = path.join(ROOT, componentName, artifact.path);
    const exists = fs.existsSync(artifactPath);

    if (exists) {
      result.existingArtifacts++;
      console.log(`  ✓ ${artifact.path}`);
    } else {
      result.missingArtifacts++;
      console.log(`  ✗ ${artifact.path} (缺失)`);
    }

    result.artifacts.push({
      path: artifact.path,
      exists,
      required: artifact.required,
      description: artifact.description
    });
  }

  // 验证质量门控
  try {
    execSync(`node scripts/phase-gate-validator.js ${componentName} ${phaseName}`, {
      cwd: ROOT,
      stdio: 'pipe'
    });
    result.gateValidation = { passed: true };
    console.log(`  ✓ 质量门控通过`);
  } catch (error) {
    result.gateValidation = { passed: false, error: error.message };
    console.log(`  ✗ 质量门控失败`);
  }

  return result;
}

function loadManifest() {
  if (!fs.existsSync(MANIFEST_PATH)) {
    throw new Error(`phase-manifest.json 不存在: ${MANIFEST_PATH}`);
  }
  return JSON.parse(fs.readFileSync(MANIFEST_PATH, 'utf8'));
}

// CLI入口
function main() {
  const componentName = process.argv[2];

  if (!componentName) {
    console.error('❌ 缺少组件名称');
    console.error('用法: npm run workflow:validate-all ComponentName');
    process.exit(1);
  }

  validateComponent(componentName).catch(error => {
    console.error(`\n❌ 验证失败: ${error.message}`);
    console.error(error.stack);
    process.exit(1);
  });
}

main();
